<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title :titleName="titleName">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="mini" @click="handleBack">返回
          </el-button>
          <el-button class="filter-item" type="primary" size="mini" @click="handleSave">保存
          </el-button>
          <el-button class="filter-item" type="primary" size="mini" @click="handleSubmit">
            <span v-if="form.stability_scheme_type != 2">提交审批</span>
            <span v-else>提交变更审批</span>
          </el-button>
          <el-button class="filter-item" type="primary" size="mini" @click="handlNextStepGo">第一页
          </el-button>
          <el-button class="filter-item" type="primary" size="mini" @click="handleBackStep">第二页
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!--稳定性试验性实验放样信息-->
      <item-title title="稳定性试验放样信息" :borderShow="false"/>

      <div class="box_table" v-for="(val,key,idx) in dataTable" :key="idx">
        <div class="title">{{val.name}}的稳定性试验放样信息</div>
        <el-table :data="val.list" border style="width: 100%">
          <el-table-column label="名称" align="center">
            <template #default="{row}">
              {{row.sample.sample_name}}
            </template>
          </el-table-column>

          <el-table-column label="批号" align="center">
            <template #default="{row}">
              {{handlSample(row.sample.batch_info)}}
            </template>
          </el-table-column>

          <el-table-column label="单倍量" align="center">
            <template #default="{row}">
              {{row.value }}{{row.sample.packaging_unit}}
            </template>
          </el-table-column>

          <el-table-column label="2倍量" align="center">
            <template #default="{row}">
              {{row.value * 2}}{{row.sample.packaging_unit}}
            </template>
          </el-table-column>

          <el-table-column label="3倍量" align="center">
            <template #default="{row}">
              {{row.value * 3}}{{row.sample.packaging_unit}}
            </template>
          </el-table-column>

        </el-table>

      </div>

      <div class="box_table">
        <div class="title">样品统计</div>
        <el-table :data="tableData" border="" class="table1" style="width: 100%"
                  @row-click="aloneClick" :cell-style="cellStyle">
          <el-table-column v-for="(cel,index) in headData" :key="index+ 'ss'"
                           :label="cel.label.label" :prop="cel.prop" align="center" width="250">
            <template v-if="cel.children.length > 0">
              <el-table-column v-for="(col,ind) in cel.children" :key="ind +'xx'" :label="col.label"
                               align="center" :column-key="col.prop + ''">
                <template slot-scope="scope">
                  <template v-if="col.label === '单倍量'">
                    {{scope.row[col.prop] === 0 ? '/':scope.row[col.prop]}}
                    {{scope.row[col.prop] === 0 ? '':col.unit}}
                  </template>
                  <template v-else-if="col.label === '使用倍数'">
                    <el-input v-if="scope.row.prop_Key === col.prop" v-model="scope.row[col.prop]"
                              :ref="col.prop"
                              @blur="(val,index,sss)=>handlBlur(scope.row[col.prop],scope.$index,col.prop)"
                              @click.native.stop placeholder="请输入倍数">
                    </el-input>
                    <span v-else>{{scope.row[col.prop]  || 0}}</span>
                  </template>
                  <template v-else-if="col.label === '小计'">
                    {{calculate(col.prop,cel.label.id,scope.$index)}}
                    {{calculate(col.prop,cel.label.id,scope.$index) === '/' ? '':col.unit}}
                  </template>
                  <template v-else>
                    {{scope.row[col.prop]}}
                  </template>
                </template>

              </el-table-column>

            </template>
          </el-table-column>

        </el-table>
        <div class="zong">
          <div class="left">
            总量
          </div>
          <div class="rigth" style="display: flex; justify-content: center;">
            <div v-for="(item,index) in headData.filter(p=>p.children.length>0)" :key="index" class="rigthBox"
                 style="flex: 1;text-align: center;">
              {{ combined(item.label.id,item.children[0].unit)}}
            </div>
          </div>
        </div>
      </div>

      <div style="text-align: center;margin-top:20px">
        <el-button class="filter-item" type="primary" size="mini" @click="handlNextStepGo">返回第一页
        </el-button>
        <el-button class="filter-item" type="primary" size="mini" @click="handleBackStep">返回第二页
        </el-button>

      </div>

      <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body
                 :before-close="cancelChange" :close-on-click-modal="false" v-if="openChange">
        <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
          <el-form-item label="变更原因" prop="change_reason"
                        :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
            <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancelChange">取 消
          </el-button>
          <el-button size="small" type="primary" @click="submitChange">
            确 定
          </el-button>
        </div>
      </el-dialog>

    </div>

  </div>
</template>

<script>
  import {
    stabilityEditor,
    createSave,
    updateSave,
    updateChangeSave,
    subApproval,
    submitChange
  } from '@/api/stability/giveUp'

  export default {
    data() {
      return {
        titleName: '创建稳定性方案',
        form: {},
        data: {},
        dataTable: {},
        tableData: [{ prop: '46545dassdsa' }],
        headData: [
          {
            label: { label: '放置条件' },
            prop: 'type',
            children: []
          }
        ],
        colums_title: [{ label: '样品A' }, { label: '样品B' }],
        rules: {
          name: [{ required: true, trigger: 'blur' }]
        },
        openChange: false,
        openChangeForm: {
          id: '',
          change_reason: ''
        },
        multiple: '',
        widthPx: null,
        stability_plan_dealInfo: {
          sample_inspect_info: [],
          dose_multiple_info: []
        }
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {
      combined() {
        return function(val, unit) {
          let sun = 0, a, b
          for (let i = 0; i < this.tableData.length; i++) {
            a = `小计-${val}`, b = this.tableData[i]
            sun += b[a]
            sun = Math.ceil(sun)
            if (isNaN(sun)) {
              sun = 0
            }
          }

          return `${sun}${unit}` || 0
        }
      },
      handlSample() {
        return function(val) {
          let str = ''
          for (let i = 0; i < val.length; i++) {
            str += val[i].sample_batch
            if (i !== val.length - 1) {
              str = str + '、'
            }
          }
          return str
        }
      }
    },
    //属性是手动定义的所需监听的值
    watch: {},
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      if (this.$route.query.id) {
        this.handlEditor()
        this.titleName = '编辑稳定性方案'
      }
    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取编辑数据
      handlEditor() {
        stabilityEditor(this.$route.query.id).then(res => {
          if (res.code === 200) {
            if (res.data.stability_table_info !== '') {
              this.data = JSON.parse(res.data.stability_table_info) || {}
            }
            this.form = res.data
            this.handlData()
            this.handlDataList()
          }
        })
      },

      //处理数据
      handlData() {
        let arr = [],
          list = []
        for (let key in this.data) {
          for (let i = 0; i < this.data[key].total.a.length; i++) {
            arr.push(this.data[key].total.a[i].arrList)
          }
        }
        if (arr.length === 0) return
        list = arr.reduce((a, b) => {
          return a.concat(b)
        })
        let data = {}, data1 = {}
        for (let j = 0; j < list.length; j++) {
          if (!data1[list[j].idts]) {
            data1[list[j].idts] = { name: list[j].name, list: [] }
          }
          let index = data1[list[j].idts].list.findIndex(a => a.sample.id == list[j].sample.id)
          if (index === -1) {
            data1[list[j].idts].list.push(list[j])
          }

          let name = `${list[j].typeName}${list[j].name}`
          let obj = {
            name: name,
            idts: list[j].idts,
            list: []
          }
          this.$set(data, name, obj)
        }

        for (let key in data) {
          data[key].list = data1[data[key].idts].list
        }

        this.dataTable = data
        let b = []
        for (let key in data) {
          let a = {
            type: data[key].name
          }
          for (let s = 0; s < data[key].list.length; s++) {
            a[data[key].list[s].sample.id] = data[key].list[s].value
          }
          b.push(a)
        }
        this.handlHead(list, b)
      },

      //生成表头
      handlHead(list, val) {
        let data = {}
        for (let i = 0; i < list.length; i++) {
          data[list[i].sample.id] = list[i].sample
        }
        let aaa = []
        for (let key in data) {
          let a = {
            label: {
              id: data[key].id,
              label: data[key].sample_name
            },
            prop: '',
            children: [
              {
                label: '单倍量',
                prop: data[key].id,
                unit: data[key].packaging_unit
              },
              {
                label: '使用倍数',
                prop: '使用倍数' + '-' + data[key].id,
                unit: data[key].packaging_unit
              },
              {
                label: '小计',
                prop: '小计' + '-' + data[key].id,
                unit: data[key].packaging_unit
              }
            ]
          }
          aaa.push(a)
        }
        this.headData = this.headData.concat(aaa)

        if (this.form.stability_scheme_type === 2) {
          this.tableData = JSON.parse(this.form.stability_plan)
        } else {
          this.handlTbale(val)
        }

      },

      //生成表格数据
      handlTbale(val) {
        let arr = [],
          data = {}
        for (let i = 0; i < this.headData.length; i++) {
          data[this.headData[i].prop] = ''
          data.boole = true
          data.prop_Key = ''
          data.unit = ''
          data.label = this.headData[i].label.label
          if (this.headData[i].children.length > 0) {
            for (let j = 0; j < this.headData[i].children.length; j++) {
              data[this.headData[i].children[j].prop] = 0
              data.unit = this.headData[i].children[0].unit
            }
          }
        }
        let keys = []
        for (let key in data) {
          let str = '使用倍数'
          if (key.search(str) != -1) {
            keys.push(key)
          }
        }
        for (let d = 0; d < val.length; d++) {
          let a = { ...data }
          arr.push(a)
          let obj1 = arr[d],
            obj2 = val[d]
          Object.keys(obj1).forEach(key => {
            obj1[key] = obj2[key] || obj1[key]
          })
        }
        let aaaaa = []
        if (this.tableData.length > 0 && this.form.stability_plan !== '') {
          if (this.form.stability_plan !== '') {
            aaaaa = JSON.parse(this.form.stability_plan) || []
          }
        }
        console.log(aaaaa,this.tableData,"---------")
        this.tableData = JSON.parse(JSON.stringify(arr))
        for (let z = 0; z < aaaaa.length; z++) {
          if (aaaaa[z].type === this.tableData[z].type) {
            for (let k = 0; k < keys.length; k++) {
              this.tableData[z][keys[k]] = aaaaa[z][keys[k]]
            }
          }
        }
        this.handlDataList()
        this.handlMultiple()
      },

      //
      calculate(prop, label, index) {
        let a = '使用倍数' + '-' + label,
          b = label
        this.multiple = a
        let c = this.tableData[index][a] * this.tableData[index][b]
        this.$set(this.tableData[index], prop, c)
        let sss = (this.tableData[index][a] * this.tableData[index][b])
        if (this.tableData[index][b] === 0) {
          sss = '/'
        } else {
          sss = Math.ceil(sss)
          if (isNaN(sss)) {
            return 0
          }
        }
        return sss
      },

      //单机行
      aloneClick(row, column, event) {
        if (this.form.stability_scheme_type == 2) return
        if (column.label && column.label === '使用倍数') {
          row.prop_Key = column.columnKey
          let sss = column.columnKey
          this.$nextTick(_ => {
            this.$refs[sss][0].focus()
          })
        } else {
          row.prop_Key = ''
        }
      },

      handlBlur(val, index, ooo) {
        let str = /^[1-2]\.[1-9]$|^[1-3]$|^[1-3]\.0$/
        if (!str.test(val)) {
          this.$message.error('使用倍数为1~3,可保留一位小数')
          this.tableData[index][ooo] = 0
        } else {
          this.tableData[index][ooo] = Number(val)
        }
        this.tableData[index].prop_Key = ''
        this.handlMultiple()
      },

      confirmTelephone(val) {
        let reg = /^\+?[1-9][0-9]*$/
        if (!reg.test(val.target.value)) {
          val.target.value = 0
        }
      },

      cellStyle(data) {
        if (this.form.stability_scheme_type == 2) return
        return 'cursor:pointer;'
      },

      //返回
      handleBack() {
        this.$route.params.refresh = true
        this.$router.push('/stability/giveUp')
      },

      //处理取样表格数据
      handlDataList() {
        let sample_inspect_info = []
        for (let key in this.data) {
          let inspect_project_ary = []
          let a = this.data[key].total.a
          this.data[key].tableData.forEach(item => {
            if (item.name.id) {
              inspect_project_ary.push(item.name)
            }
          })
          for (let i = 0; i < a.length; i++) {
            for (let j = 0; j < a[i].arrList.length; j++) {
              let data = {
                inspect_type_id: a[i].arrList[j].inspection_type_id,
                sample_info: a[i].arrList[j].sample_info,
                place_conditions_id: a[i].arrList[j].place_conditions_id,
                place_conditions_type_id: a[i].arrList[j].place_conditions_type_id,
                num: a[i].arrList[j].value,
                id: a[i].arrList[j].id,
                name: a[i].arrList[j].typeName + a[i].arrList[j].name,
                inspect_project_ary: inspect_project_ary
              }
              sample_inspect_info.push(data)
            }
          }

        }

        this.stability_plan_dealInfo.sample_inspect_info = sample_inspect_info
      },

      //处理倍数
      handlMultiple() {
        this.handlDataList()
        let dose_multiple_info = []
        let arr = this.stability_plan_dealInfo.sample_inspect_info
        let ids = []
        console.log(arr,this.tableData,"---rewrewr-----------")
        for (let i = 0; i < arr.length; i++) {
          let aa = arr[i]

          for (let j = 0; j < this.tableData.length; j++) {
            let bb = this.tableData[j]
            if (aa.name === bb.type) {
              // ids.push(aa.sample_info.id)
              let c = `使用倍数-${aa.sample_info.id}`
              let data = {
                place_conditions_type_id: aa.place_conditions_type_id,
                place_conditions_id: aa.place_conditions_id,
                multiple: bb[c],
                sample_info: aa.sample_info
              }
              dose_multiple_info.push(data)
            }
          }
        }
        this.stability_plan_dealInfo.dose_multiple_info = dose_multiple_info
      },

      //保存
      handleSave() {
        this.form.stability_plan = JSON.stringify(this.tableData)
        this.form.stability_plan_deal_info = this.stability_plan_dealInfo
        this.form.stability_plan_deal_info.sample_inspect_info.forEach(item => {
          this.$delete(item, 'id')
          this.$delete(item, 'name')
        })
        let commit = undefined,
          msg = ''
        if (this.$route.query.type == 1) {
          commit = updateSave
          msg = '保存成功'
        } else if (this.$route.query.type == 2) {
          commit = updateChangeSave
          msg = '方案变更保存成功'
        } else {
          commit = createSave
          msg = '创建保存成功'
        }
        commit(this.form).then(res => {
          if (res.code == 200) {
            this.$message.success(msg)
            if (commit === updateChangeSave) {
              this.$route.params.refresh = true
              this.$router.push('/stability/giveUp')
            }
          } else {
            this.$message.error(res.msg)
          }
        })
      },

      //提交审核
      handleSubmit() {
        let ssss = this.handlTree()
        if (ssss.boole) {
          this.$message.error(ssss.msg)
          return
        }
        // if (this.form.stability_instrument_infos.length === 0) {
        //   this.$message.error('请至少选择一个稳定性仪器')
        //   return
        // }

        let aaa = this.handlTableCharm(this.data)
        if (!aaa) return
        this.form.stability_plan = JSON.stringify(this.tableData)
        this.form.stability_plan_deal_info = this.stability_plan_dealInfo
        this.form.stability_plan_deal_info.sample_inspect_info.forEach(item => {
          this.$delete(item, 'id')
          this.$delete(item, 'name')
        })
        let bbb = this.handlStableCharm(this.tableData)
        if (!bbb) return
        if (this.form.stability_scheme_type === 2) {
          this.openChange = true
        } else {
          updateSave(this.form).then(res => {
            if (res.code === 200) {
              subApproval(this.form.id).then(res => {
                if (res.code === 200) {
                  this.$message.success('提交审核成功')
                  this.$route.params.refresh = true
                  this.$router.push('/stability/giveUp')
                } else {
                  this.$message.error(res.msg)
                }
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      },

      //变更审核取消
      cancelChange() {
        this.openChangeForm = {
          id: '',
          change_reason: ''
        }
        this.openChange = false
      },

      //变更审核提交
      submitChange() {
        this.$refs.openChangeForm.validate(valid => {
          if (valid) {
            this.openChangeForm.id = this.$route.query.id
            submitChange(this.openChangeForm).then(res => {
              if (res.code === 200) {
                this.$message.success('提交变更审批成功')
                this.$route.params.refresh = true
                this.$router.push('/stability/giveUp')
                this.cancelChange()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },

      //返回上上一步
      handlNextStepGo() {
        this.form.stability_plan = JSON.stringify(this.tableData)
        if (this.$route.query.id) {
          updateSave(this.form).then(res => {
            if (res.code === 200) {
              this.$router.push({
                path: '/stability/giveUp/created',
                query: { id: this.$route.query.id, type: this.$route.query.type }
              })
            }
          })
        }
      },

      //返回上一步
      handleBackStep() {
        this.form.stability_plan = JSON.stringify(this.tableData)
        if (this.$route.query.id) {
          updateSave(this.form).then(res => {
            if (res.code === 200) {
              this.$router.push({
                path: '/stability/giveUp/tableDetail',
                query: { id: this.$route.query.id, type: this.$route.query.type }
              })
            }
          })
        }
      },

      //效验检查项目表明细
      handlTableCharm(val) {
        let aa, bb, cc, dd
        for (let key in val) {
          let dic = {}
          aa = key.split('?')
          let index = this.form.stability_details.findIndex(
            a => a.stability_sample_info.id == aa[0]
          )
          if (index !== -1) {
            bb = this.form.stability_details[index].label
            let index1 = this.form.stability_details[
              index
              ].inspect_types.findIndex(a => a.inspect_type.id == aa[1])
            if (index1 !== -1) {
              cc = this.form.stability_details[index].inspect_types[index1]
                .inspect_type.inspect_type_name
              dd = bb + cc + '未勾选取样点'
            }
          }
          for (let i = 0; i < val[key].tableData.length; i++) {
            if (i != val[key].tableData.length - 1) {
              let sss = val[key].tableData[i]
              let bo = false
              for (let obj in sss) {
                if (obj !== 'name' && obj !== 'num' && obj !== 'boole') {
                  let obj1 = obj.split('-')[0]
                  if (val[key].headList === null || val[key].headList.length === 0) {
                    bo = true
                  } else {
                    let zzz = val[key].headList.findIndex(a => a == obj1)
                    if (zzz !== -1) {
                      if (typeof sss[obj] != 'string') {
                        if (!dic[obj] && typeof dic[obj] != 'bool') {
                          dic[obj] = false
                        }
                        if (sss[obj]) {
                          bo = true
                          dic[obj] = true
                          continue
                        }
                      }
                    }
                  }
                }
              }
              if (!bo) {
                this.$message.error(dd)
                return false
              }
            }
          }
          for (let a in dic) {
            if (!dic[a]) {
              this.$message.error(dd)
              return false
            }
          }
        }
        return true
      },

      //效验稳定性试验放样信息
      handlStableCharm(val) {
        for (let i = 0; i < val.length; i++) {
          let obj = val[i]
          for (let key in obj) {
            if (key.indexOf('使用倍数') != -1) {
              let sss = key.split('-')
              if (sss.length > 1 && obj[sss[1]] !== 0) {
                if (obj[key] == 0 || obj[key] == undefined) {
                  this.$message.error('样品统计使用倍数不能为0')
                  return false
                }
              }
            }
          }
        }
        return true
      },

      //验证tree
      handlTree() {
        var boole, msg
        if (this.form.sample_list == null) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        }
        if (this.form.sample_list.length === 0) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        } else {
          let aaa = this.form.stability_details
          if (aaa.length === 0) {
            msg = '请勾选样品'
            boole = true
            return { boole: boole, msg: msg }
          } else {
            for (let i = 0; i < aaa.length; i++) {
              let bbb = aaa[i].conditions
              if (bbb.length === 0) {
                msg = `请勾选${aaa[i].label}的考察类型`
                boole = true
                return { boole: boole, msg: msg }
              } else {
                for (let j = 0; j < bbb.length; j++) {
                  if (bbb[j].conditions.length === 0) {
                    msg = `请勾选${bbb[j].label}的放置条件`
                    boole = true
                    return { boole: boole, msg: msg }
                  }
                }
              }
            }
          }
        }
        return { boole: false }
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  .title {
    line-height: 50px;
  }

  ::v-deep .el-table__expanded-cell[class*="cell"] {
    padding: 0 !important;
    border: none;
  }

  ::v-deep
  .el-table__expanded-cell[class*="cell"]
  .el-table__row
  td:first-of-type {
    border-bottom: none;
  }

  ::v-deep .el-button--text {
    padding: 0 !important;
  }

  ::v-deep .table1 tr td {
    padding: 0 !important;
    height: 48px !important;
    overflow: visible !important;
    line-height: 48px;
  }

  ::v-deep .table1 tr td .cell {
    height: 30px !important;
    overflow: visible !important;
    line-height: 30px;
  }

  ::v-deep .item_form {
    overflow: hidden;
  }

  .zong {
    width: 100%;
    height: 48px;
    border: 1px solid #ebeef5;
    border-top: none;
    display: flex;
    align-items: center;
    box-sizing: border-box;
  }

  .left {
    width: 250px;
    height: 48px;
    border-right: 1px solid #ebeef5;
    box-sizing: border-box;
    line-height: 48px;
    padding-left: 20px;
    font-size: 12px;
    text-align: center;
  }

  .rigth {
    width: calc(100% - 250px);
    height: 48px;
    font-size: 12px;
    display: flex;
  }

  .rigthBox {
    height: 48px;
    line-height: 48px;
    border-right: 1px solid #ebeef5;
  }

  .rigthBox:last-child {
    border: none;
  }
</style>
